import * as VueRouter from 'vue-router'
import modules from './modules'
import useUserStore from '@/store/user'
import { redirctToLogin } from '@/utils/auth'
import usePermissionStore from '@/store/permission'
import { hasPermission, parseLayoutMenu, getAllLayoutMenu } from './utils/permise'
import {pareseCenterMenuToGroup} from './utils'
import { getUrlParams } from '@/utils'
import NProgress from 'nprogress'

const USE_ALL = true
let isInit = false
const router = VueRouter.createRouter({
  history: VueRouter.createWebHistory(),
  routes: modules,
  scrollBehavior () {
    return {top: 0}
  }
})
/**路由白名单 */
const WHITE_PATHS = ['/404', '/login', '/test*']

const whitePathReg: RegExp[] = []

WHITE_PATHS.forEach((path) => {
  if (path.indexOf('*') > -1) {
    whitePathReg.push(new RegExp('^' + path.replace('*', '+')))
  } else {
    whitePathReg.push(new RegExp('^' + path + '$'))
  }
})

/**
 * 是否为白名单
 */
const isWhitePath = (fullPath: string) => {
  return whitePathReg.some(reg => reg.test(fullPath))
}
router.beforeEach(async (to) => {
  NProgress.start()
  const userStore = useUserStore()
  // 判断URL上是否有ticket参数
  const urlParams = getUrlParams()
  if (urlParams.ticket) {
    await userStore.login({
      ticket: urlParams.ticket,
      test: import.meta.env.VITE_TEST
    })
    history.replaceState('', '', location.href.replace(location.search, '').replace(import.meta.env.VITE_FRONT_SUBURL || '', ''))
  }
  if (isWhitePath(to.path)) {
    return true
  }
  const permissionStore = usePermissionStore()
  // TODO 获取用户信息优先级
  // 判断用户是否登录
  if (userStore.hasToken()) {
    if (!isInit) {
      // 获取用户信息
      await userStore.getUserInfo()
      if (!USE_ALL) {
        // 判断用户是否获取权限数据
        const permiseMenu = await permissionStore.getPermissonMenu()
        // 菜单设置
        parseLayoutMenu(permiseMenu)
      } else {
        getAllLayoutMenu()
      }
      isInit = true
      pareseCenterMenuToGroup()
    }
    if (hasPermission(to)) { // 是否有权限
      return true
    } else { // 无权限跳转至403
      return {path: '/403'}
    }
  } else {
    return redirctToLogin()
  }
})

router.afterEach((to) => {
  // 设置标题，浏览历史记录
  const userStore = useUserStore()
  const groups = userStore.groupCenterMenus
  for (let item of groups) {
    if (item.names.includes(to.name) || item.names.includes(to.meta.parent)) {
      let menu = item.leafs.filter((el:any) => el.name === to.name)[0]
      if (userStore.currentHisPages.key !== item.key) {
        userStore.currentHisPages.menus = [menu]
        userStore.currentHisPages.key = item.key
      } else {
        if (!userStore.currentHisPages.menus.some(el => el.name === to.name)) {
          userStore.currentHisPages.menus.push(menu)
        }
      }
      document.title = to.meta.title || menu.title
      break
    }
  }

  NProgress.done()
})

export default router
